package com.simtop.hj.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.simtop.hj.common.ServerResponse;
import com.simtop.hj.pojo.*;
import com.simtop.hj.service.UserService;
import com.simtop.hj.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import static com.auth0.jwt.internal.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data;

@CrossOrigin
@Controller
@RequestMapping(value = "/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserService userService;


    @Autowired
    public RedisUtil redisUtil;


    /**
     * 获取角色身份
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRole", method = RequestMethod.GET)
    public ServerResponse<List<Role>> getRole() {
        List<Role> roleList = userService.getRole();
        return ServerResponse.createBySuccess(roleList);
    }


    /**
     * 用户登录（返回类）
     *
     * @param user（loginName，password，roleId）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ServerResponse<String> login(@RequestBody User user) {
        logger.info("登录" + user);
        User loginUser = userService.login(user);
        if (EmptyUtil.isNotEmpty(loginUser)) {
            loginUser.setLoginTime(System.currentTimeMillis());
//            loginUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);//置空密码
            // todo important token有效期10个小时
            String token = JwtUtil.sign(loginUser, 6000L * 1000L * 6L);//token有效期10小时
            return ServerResponse.createBySuccess(token);
        } else {
            return ServerResponse.createByErrorMsg("账号名或者密码输入错误");
        }
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ServerResponse<String> register(@RequestBody User user) {
        logger.info("注册用户" + user);
        return userService.register(user);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = JSONObject.parseObject(email);
        logger.info("email" + jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.generateCheckCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forgetCheckCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = JSONObject.parseObject(email);
        logger.info("email" + jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody User user) {
        return userService.updatePassword(user);
    }


    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse addUser(@RequestBody User user) {
        return userService.addUser(user);
    }


    /**
     * 游客登录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "expertLogin", method = RequestMethod.POST)
    public ServerResponse<String> expertLogin() {
        User expertLoginUser = new User();
        expertLoginUser.setRoleId(4);
        expertLoginUser.setUsername("评审账户");
        expertLoginUser.setLoginName("pszh" + System.currentTimeMillis());
        expertLoginUser.setPassword("mima" + System.currentTimeMillis());
        expertLoginUser.setLoginTime(System.currentTimeMillis());
        userService.expertLogin(expertLoginUser);
        logger.info("用户信息" + expertLoginUser);
//        expertLoginUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);//置空密码
        String token = JwtUtil.sign(expertLoginUser, 6000L * 1000L * 6L);//token有效期60分钟
//        Integer touristNums=0;
//        if(redisTemplate.hasKey("touristNums")){
//            touristNums=Integer.parseInt(redisTemplate.boundValueOps("touristNums").get());
//        }
//        redisTemplate.boundValueOps("touristNums").set(String.valueOf(++touristNums));
        return ServerResponse.createBySuccess(token);
    }


    /**
     * 管理员搜索用户+查看用户
     *
     * @param request
     * @param searchUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUser", method = RequestMethod.POST)
    public ServerResponse<PageInfo> searchUser(HttpServletRequest request, @RequestBody String searchUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(searchUser);
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageNum = jsonObject.getInteger("pageNum");
        String loginName = jsonObject.getString("loginName");
        String username = jsonObject.getString("username");
        String subjects = jsonObject.getString("subjects");
        String studyYear = jsonObject.getString("studyYear");
        return userService.searchUser(pageNum, pageSize, username, subjects, loginName, studyYear);
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public ServerResponse updateUser(HttpServletRequest request, @RequestBody User user) {
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        return userService.updateUser(user);
    }

    /**
     * 删除用户
     *
     * @param request
     * @param deleteUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public ServerResponse deleteUser(HttpServletRequest request, @RequestBody String deleteUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(deleteUser);
        String ids = jsonObject.getString("id");
        String[] array = ids.substring(1,ids.length()-1).split(",");
        System.out.println(Arrays.toString(array));
        try{
            for(String arr:array){
                Integer integer = Integer.valueOf(arr);
                userService.deleteUser(integer);
            }
            return ServerResponse.createBySuccess();
        }catch (Exception e){
            return ServerResponse.createByError();
        }
    }

    /**
     * 刷新自增访问人数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/refresh", method = RequestMethod.POST)
    public ServerResponse refreshNums() {
        Integer refreshNums = 0;
        if (redisUtil.hasKey("refreshNums")) {
            refreshNums = (Integer) redisUtil.get("refreshNums");
        }
        redisUtil.set("refreshNums", ++refreshNums);
        return ServerResponse.createBySuccess();
    }

    /**
     * 首页数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getIndexData", method = RequestMethod.POST)
    public ServerResponse getIndexData() {
        Integer experimentCount = userService.getExperiment();
        List<WineWorld> indexData = userService.getIndexData();
        Echarts3 echarts3 = userService.selectScoreUser();//用户成绩分布
        Integer nums = 0;
        if (redisUtil.hasKey("nums")) {
            nums = (Integer) redisUtil.get("nums");
        }
        redisUtil.set("nums", ++nums);
        Integer userNums = 0;
        for (int i = 0; i < indexData.size(); i++) {
            userNums += indexData.get(i).getValue();
        }
        Echarts1 echarts = new Echarts1();
        echarts.setWineWorldList(indexData);
        echarts.setUserNums(userNums);
        echarts.setNums(nums);
        echarts.setExperimentCount(experimentCount);
        echarts.setEcharts3(echarts3);
        return ServerResponse.createBySuccess(echarts);
    }

    /**
     * 生成成绩单
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createReportCard", method = RequestMethod.POST)
    public ServerResponse createReportCard(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        Grade grade = new Grade();
        grade.setUserId(u.getId());
//        grade.setScore(100);
        grade.setUsername(u.getUsername());
        grade.setGradeExperimentDate(new Date());
//        grade.setGradeExperimentTime((int) ((System.currentTimeMillis())/1000/60));
        grade.setGradeExperimentTime((int) ((System.currentTimeMillis() - (long) redisUtil.get(u.getId() + "experiment")) / 1000 / 60));
//        userService.createReportCard(grade);
        return ServerResponse.createBySuccess(grade);
    }


    /**
     * 提交评论
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addComment", method = RequestMethod.POST)
    public ServerResponse addComment(HttpServletRequest request, @RequestBody String addComment) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(addComment);
        String cognition = jsonObject.getString("cognition");
        String skill = jsonObject.getString("skill");
        String field = jsonObject.getString("field");
        String modeling = jsonObject.getString("modeling");
        String thinking = jsonObject.getString("thinking");
//        Integer gradeId=jsonObject.getInt("gradeId");
        Integer commentScore = jsonObject.getInteger("commentScore");
        Integer gradeExperimentTime = jsonObject.getInteger("gradeExperimentTime");
        Integer score = jsonObject.getInteger("score");
        Integer theoreticalStudyScore = jsonObject.getInteger("theoreticalStudyScore");//理论学习信息分数
        Integer fetchingInfoScore = jsonObject.getInteger("fetchingInfoScore");//数据抓取信息分数
        Integer cleaningInfoScore = jsonObject.getInteger("cleaningInfoScore");//数据清洗信息分数
        Integer analysisScore = jsonObject.getInteger("analysisScore");//数据分析信息分数
        Grade grade = new Grade();
        grade.setCognition(cognition);
        grade.setSkill(skill);
        grade.setField(field);
        grade.setModeling(modeling);
        grade.setThinking(thinking);
//        grade.setGradeId(gradeId);
        grade.setCommentScore(commentScore);
        grade.setGradeExperimentTime(gradeExperimentTime);
        grade.setScore(score);
        grade.setTheoreticalStudyScore(theoreticalStudyScore);
        grade.setFetchingInfoScore(fetchingInfoScore);
        grade.setCleaningInfoScore(cleaningInfoScore);
        grade.setAnalysisScore(analysisScore);

        grade.setGradeExperimentDate(new Date());
        grade.setUserId(u.getId());
        grade.setUsername(u.getUsername());
        return userService.addComment(grade);
    }


    /**
     * 提交成绩
     *
     * @param request
     * @param grade
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addScore", method = RequestMethod.POST)
    public ServerResponse addScore(HttpServletRequest request, @RequestBody Grade grade) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        grade.setUserId(u.getId());
        grade.setUsername(u.getUsername());
        return userService.addScore(grade);
    }


    /**
     * 获取成绩
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getGrade", method = RequestMethod.POST)
    public ServerResponse<PageInfo<Grade>> getGrade(HttpServletRequest request, @RequestBody String grades) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(grades);
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageNum = jsonObject.getInteger("pageNum");
        String username = jsonObject.getString("username");
        String subjects = jsonObject.getString("subjects");
        String classes = jsonObject.getString("classes");
        String studyYear = jsonObject.getString("studyYear");
        String loginName = jsonObject.getString("loginName");
        u.setUsername(username);
        u.setSubjects(subjects);
        u.setClasses(classes);
        u.setStudyYear(studyYear);
        u.setLoginName(loginName);
        return userService.getGrade(pageSize, pageNum, u);
    }


    /**
     * 根据编号来删除成绩
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteGrade", method = RequestMethod.POST)
    public ServerResponse deleteGrade(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer gradeId = jsonObject.getInteger("gradeId");
        return userService.deleteGrade(gradeId);
    }


    /**
     * 下载成绩记录
     *
     * @param response
     */
    @RequestMapping(value = "/downLoadGrade", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadOperateInfo(HttpServletResponse response,@ModelAttribute User user,HttpServletRequest request) {
        ServletOutputStream out = null;
        List<DownGrade> downGradeList = userService.downLoadGrade(user);
        /**
         * 处理计算
         */
        downGradeList.forEach(
               downGrade -> {
                   if(downGrade.getScoreArray()==null){
                       downGrade.setCognitiveValuePrice(null);
                       downGrade.setCompetitiveAnalysisPricing(null);
                       downGrade.setMachineLearningPricing(null);
                       downGrade.setGrowthProductPricing(null);
                   }else{
                       String[] arr = downGrade.getScoreArray().split(",");
                       List<Integer> i = new ArrayList<Integer>(14);
                       for (String a:arr){
                           i.add(Integer.valueOf(a));
                       }
                       try{
                           downGrade.setCognitiveValuePrice(i.get(0)+i.get(1)+i.get(2)+i.get(3));
                           downGrade.setCompetitiveAnalysisPricing(i.get(4)+i.get(5)+i.get(6));
                           downGrade.setMachineLearningPricing(i.get(7)+i.get(8)+i.get(9)+i.get(10));
                           downGrade.setGrowthProductPricing(i.get(11)+i.get(12)+i.get(13));
                       }catch (Exception e){
                           downGrade.setCognitiveValuePrice(0);
                           downGrade.setCompetitiveAnalysisPricing(0);
                           downGrade.setMachineLearningPricing(0);
                           downGrade.setGrowthProductPricing(0);
                       }
                   }
                   if(StringUtils.isEmpty(downGrade.getComment()) || downGrade.getComment()==null){
                       downGrade.setCognitiveValuePrice(null);
                   }else{
                       JSONObject jsonObject = JSONObject.parseObject(downGrade.getComment());
                       StringBuilder sb = new StringBuilder();
                       System.out.println("123"+jsonObject.getString("firstQuestion")+"456");
                       if (jsonObject.getString("firstQuestion") == "" || jsonObject.getString("firstQuestion") == null) {
                           sb.append("第一题：无内容,");
                       } else {
                           sb.append("第一题：" + jsonObject.getString("firstQuestion")+",");
                       }
                       if (jsonObject.getString("secondQuestion") == "" || jsonObject.getString("secondQuestion") == null) {
                           sb.append("第二题：无内容,");
                       } else {
                           sb.append("第二题：" + jsonObject.getString("secondQuestion")+",");
                       }
                       if (jsonObject.getString("thirdQuestion") == "" || jsonObject.getString("thirdQuestion") == null) {
                           sb.append("第三题：无内容,");
                       } else {
                           sb.append("第三题：" + jsonObject.getString("thirdQuestion")+",");
                       }
                       if (jsonObject.getString("fourthQuestion") == "" || jsonObject.getString("fourthQuestion") == null) {
                           sb.append("第四题：无内容,");
                       } else {
                           sb.append("第四题：" + jsonObject.getString("fourthQuestion")+",");
                       }
                       if (jsonObject.getString("fifthQuestion") == "" || jsonObject.getString("fifthQuestion") == null) {
                           sb.append("第五题：无内容,");
                       } else {
                           sb.append("第五题：" + jsonObject.getString("fifthQuestion")+",");
                       }
                       downGrade.setComment(sb.toString());
                   }
               }
        );
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "实验成绩记录";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            ExcelUtils.writeExcel(out, DownGrade.class, downGradeList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 下载用户上传模板
     *
     * @param response
     */
    @RequestMapping(value = "/downLoadUser", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadUser(HttpServletResponse response) {
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "用户上传模板";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            ExcelUtils.writeExcel(out, DownUser.class, null);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 导入用户表
     * @param file
     * @param sourceId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadUser", method = RequestMethod.POST)
    public ServerResponse upload(MultipartFile file, Integer sourceId, HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return ServerResponse.createByErrorMsg("文件为空");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            logger.info("文件的后缀名为：" + suffixName);
            //创建一个临时文件，用于暂时存放
            File tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, DownUser.class);
                if (objectList == null) {
                    logger.info("数据有误");
                    return ServerResponse.createByErrorMsg("数据有误，上传失败");
                }else{
                    List<DownUser> downUserList=new ArrayList<>();
                    for (int i = 0; i < objectList.size(); i++) {
                        DownUser downUser= (DownUser) objectList.get(i);
                        if(downUser.getUsername()!=null&&downUser.getLoginName()!=null&&downUser.getEmail()!=null&&downUser.getPassword()!=null
                        &&downUser.getSchool()!=null&&downUser.getClasses()!=null
                        &&downUser.getSubjects()!=null&&downUser.getStudyYear()!=null){
                            downUserList.add(downUser);
                        }
                    }
                    for (int i = 0; i < downUserList.size(); i++) {
                        DownUser downUser= (DownUser) downUserList.get(i);
                        User user=new User();
                        user.setLoginName(downUser.getLoginName());
                        user.setUsername(downUser.getUsername());
                        user.setPassword(downUser.getPassword());
                        user.setEmail(downUser.getEmail());
                        user.setCity(downUser.getCity());
                        user.setSchool(downUser.getSchool());
                        user.setProvince(downUser.getProvince());
                        user.setCity(downUser.getCity());
                        user.setClasses(downUser.getClasses());
                        user.setSubjects(downUser.getSubjects());
                        user.setRoleId(3);
                        user.setStudyYear(downUser.getStudyYear());
                        user.setPhone(downUser.getPhone());
                        userService.registerUser(user);
                    }
                }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess("添加成功！");
    }
}
